package com.example.com.skills_utf8;




import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.sax.StartElementListener;
import android.widget.TextView;

import com.utils.Utils1;





// http://www.cnblogs.com/freeliver54/archive/2011/12/13/2285980.html
// http://www.oschina.net/question/565065_68240
public class BluetoothServerActivity  extends Activity{

	private BluetoothAdapter btAdapt;
	private String BluetoothServerName ="BP";
	private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

	private int DISCOVERY = 0x4000;
	
	
	TextView tv_uuid ;
	Handler UI_handler = new Handler(){
		
		public void handleMessage(android.os.Message msg) {
			
		};
	};
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		
		tv_uuid = new TextView(this);
		setContentView(tv_uuid);
		
		
		
		// 开启蓝牙
			this.btAdapt = BluetoothAdapter.getDefaultAdapter();
			if (this.btAdapt == null) {
				Utils1.showToastShort(this, "您的机器上没有发现蓝牙适配器，本程序将不能运行!");
				return;
			}

			boolean bOpened =this.btAdapt.enable();  // 不提示,直接打开
			System.out.println("开启状态:"+bOpened);
			System.out.println("name: "+btAdapt.getName());
			System.out.println("mac: "+btAdapt.getAddress());
			
			// 使可被发现
			Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
			enabler.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
			this.startActivityForResult(enabler, DISCOVERY);
			
			
			BluetoothServert tcp_server;
			try {
				tcp_server = new BluetoothServert(btAdapt,BluetoothServerName, uuid);
				tcp_server.start();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		
		if(requestCode == this.DISCOVERY){
	//		String action =data.getAction();
	//		System.out.println(action);
			
				
		}
		
		
	}
	
	/*
	public QzjProcesst(Activity activity, Handler handle) 
	{
		
		// 
		
		
		// 开启蓝牙
		this.btAdapt = BluetoothAdapter.getDefaultAdapter();
		if (this.btAdapt == null) {
			Utils1.showToastShort(activity, "您的机器上没有发现蓝牙适配器，本程序将不能运行!");
			return;
		}

		boolean bOpened =this.btAdapt.enable();  // 不提示,直接打开
		boolean bDiscover =btAdapt.isDiscovering(); 
		System.out.println("可被发现:"+bDiscover);
		System.out.println("开启状态:"+bOpened);
		System.out.println("name: "+btAdapt.getName());
		System.out.println("mac: "+btAdapt.getAddress());
		
		Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
		activity.startActivity(enabler);
		
		
		BluetoothServert tcp_server;
		try {
			tcp_server = new BluetoothServert(btAdapt,BluetoothServerName, uuid);
			tcp_server.start();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	*/

	
	

	
}



// DataInputStream  不是线程安全的.
// java多线程就是开辟多个对象. 这种代码共享和c++中的不一样? 答:应该是一样的new出的仅仅是新数据.
//

class SessionThread extends Thread {
	BluetoothSocket clientSocket;
	boolean m_bDO =false;
	boolean m_bConnectDB =false;
	
	byte[] client_byte= new byte[1024];
	
	DataInputStream dis =null;
	
	String client_address;
	String client_name;
	
	SessionThread(BluetoothSocket s) throws IOException {
		clientSocket = s;
		m_bDO =true;
		
	//	m_bConnectDB =connect_db();
		
		OutputStream os =clientSocket.getOutputStream();
		os.write("hello".getBytes()); // 向连入的客户端Say Hello
	//	os.close(); //不需要
		
		client_address =clientSocket.getRemoteDevice().getAddress();
		client_name =clientSocket.getRemoteDevice().getName();
		System.out.println("enter mac: "+client_address); 
		System.out.println("enter name: "+client_name); 
		
		dis = new DataInputStream(
				clientSocket.getInputStream());
		
		
	}

	public void run() {

		// 从客户端获取数据

		while ( m_bDO ) {

	///*1 通道正确建立	  OK
		//	String data = null;
			try {
 
					
			//		Arrays.fill(client_byte, (byte)0);
					
					if(dis == null && !clientSocket.isConnected()) 
						return;
					
					
				//	data = dis.readUTF(); // 接收客户端发送过来的数据.
					int j =dis.read(client_byte);
				
					if( j != -1 ){ //or -1 if there is no more data because the end of the stream has been reached. 
		

						String recv =new String(client_byte, 0, j);
					System.out.println(	recv );  //new String(client_byte.toString())			
					
					
					do_input_data(recv);
					
				//	do_db();
					
					}
					else
					{
						System.out.println("quit:"+client_address);
						
						close_db();
						dis.close();
						clientSocket.close();
						m_bDO =false;
						
					}
		
					

			} catch (IOException e) {
				// TODO Auto-generated catch block
			//	System.err.println("err. Client:"+client_address);
				System.out.println("out. Client:"+client_address);
				e.printStackTrace(); // 在这里处理超时  关闭该线程.
				
				close_db();
				m_bDO =false; // read有异常就断掉.
			}
		//1*/	
			
		}// end while

	} // end run
	
	
	void close_db(){
		
	}
	
	
	
//	Calendar rightNow = Calendar.getInstance() ;
	
	ArrayList<String> list = new ArrayList<String>();
	String DeviceID;
	String UserID;
	String DeviceFlag;
	
	
	long TimeStamp;
	String dateStr;
	
	
	boolean isBegine ;
	boolean isCorrect;
	void do_input_data(String data) //const 
	{
		
		list.clear();
		
	
		
		
	}// end do_input_data()
	

}

// TCP服务器, 接入客户端, 吸收数据
class BluetoothServert extends Thread {
	
	private BluetoothServerSocket m_ServerSocket;
	private boolean m_bDO =false;

	
	BluetoothServert(BluetoothAdapter btAdapt, String BluetoothServerName, UUID uuid) throws IOException {
		// clientSocket =s;
		
		// 创建服务端套接字
		m_ServerSocket = btAdapt.listenUsingRfcommWithServiceRecord(BluetoothServerName, uuid);
		m_bDO =true;
	}


	public void run() {

		// 从客户端获取数据

		String data = null;
		while(m_bDO)
		{
			try {  
				System.out.println("accepting...");
				BluetoothSocket clinet = m_ServerSocket.accept();
	//clinet.setSoTimeout(3000);
				// 单开个会话处理
				new SessionThread(clinet).start();


			} catch (IOException e) {
				// TODO Auto-generated catch block
				
				System.out.println("Server:");
				e.printStackTrace();
			}		
			
		}
		

	}

} //end BluetoothServert














